import {
  entityTableSelector,
  entityDetailsButtonSelector,
  entityDetailsBackButtonSelector,
  <%_ if (!readOnly) { _%>
  entityCreateButtonSelector,
  entityCreateSaveButtonSelector,
  entityEditButtonSelector,
  entityDeleteButtonSelector,
  entityConfirmDeleteButtonSelector,
  <%_ } _%>
} from '../../support/entity';
<%_
const baseApi = (applicationType === 'gateway' && locals.microserviceName) ? 'services/' + microserviceName.toLowerCase() + '/api/' : 'api/';
let openBlockComment = ``;
let closeBlockComment = ``;

for (let relationship of relationships) {
  if (relationship.relationshipRequired || relationship.useJPADerivedIdentifier) {
    openBlockComment = `/* this test is commented because it contains required relationships`;
    closeBlockComment = `*/`;
    break;
  }
}

let entityFakeData;
if (!openBlockComment) {
  resetFakerSeed('entity-cypress');
  entityFakeData = generateFakeData('cypress');
  if (!entityFakeData) {
    openBlockComment = `/* this test is commented because it failed to generate a correct full sample`;
    closeBlockComment = `*/`;
  }
}
_%>

describe('<%= entityClass %> e2e test', () => {
  let startingEntitiesCount = 0;

  <%_ if (authenticationType === 'oauth2') { _%>
  beforeEach(() => {
    cy.clearCache();
    cy.keycloackLogout();
    cy.visit('/');
    cy.keycloackLogin('user');
    cy.clickOnLoginItem();
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest').its('responseBody').then(array => {
      startingEntitiesCount = array.length;
    });
    cy.visit('/');
  });
  <%_ } else { _%>
  before(() => {
    cy.window().then((win) => {
      win.sessionStorage.clear()
    });
    <%_ if (authenticationType === 'session') { _%>cy.clearCookie('SESSION')<% } %>
    cy.clearCookies();
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('');
    cy.login('admin', 'admin');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest').its('responseBody').then(array => {
      startingEntitiesCount = array.length;
    });
    cy.visit('/');
  });
  <%_ } _%>

  it('should load <%= entityClassPlural %>', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest');
    cy.getEntityHeading('<%= entityClass %>').should('exist');
    if (startingEntitiesCount === 0) {
      cy.get(entityTableSelector).should('not.exist');
    } else {
      cy.get(entityTableSelector).should('have.lengthOf', startingEntitiesCount);
    }
    cy.visit('/');
  });

  it('should load details <%= entityClass %> page', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest');
    if (startingEntitiesCount > 0) {
      cy.get(entityDetailsButtonSelector).first().click({force: true});
      cy.getEntityDetailsHeading('<%= entityInstance %>');
      cy.get(entityDetailsBackButtonSelector).should('exist');
    }
    cy.visit('/');
  });

  <%_ if (!readOnly) { _%>
  it('should load create <%= entityClass %> page', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest');
    cy.get(entityCreateButtonSelector).click({force: true});
    cy.getEntityCreateUpdateHeading('<%= entityClass %>');
    cy.get(entityCreateSaveButtonSelector).should('exist');
    cy.visit('/');
  });

  it('should load edit <%= entityClass %> page', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest');
    if (startingEntitiesCount > 0) {
      cy.get(entityEditButtonSelector).first().click({force: true});
      cy.getEntityCreateUpdateHeading('<%= entityClass %>');
      cy.get(entityCreateSaveButtonSelector).should('exist');
    }
    cy.visit('/');
  });

  <%= openBlockComment %>
  it('should create an instance of <%= entityClass %>', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest');
    cy.get(entityCreateButtonSelector).click({force: true});
    cy.getEntityCreateUpdateHeading('<%= entityClass %>');
    <%_ fields.forEach((field) => {
      const fieldName = field.fieldName;
      const fieldNameCapitalized = field.fieldNameCapitalized;
      const fieldType = field.fieldType;
      const fieldTypeBlobContent = field.fieldTypeBlobContent;
      const fieldIsEnum = field.fieldIsEnum;
      const fieldValue = !entityFakeData ? field.generateFakeData('cypress') : entityFakeData[field.fieldName];
      if (fieldValue === undefined) {
          warning(`Error generating a value for field ${fieldName}`);
          return;
      }
    _%>

    <%_ if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('<%= fieldValue %>').invoke('val').should('equal', '<%= fieldValue %>');

    <%_ } else if (fieldType === 'Duration' && clientFramework === 'react') { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('PT12S').should('have.value', 'PT12S');

    <%_ } else if (fieldType === 'Duration' && clientFramework !== 'react') { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('PT12S').should('have.value', 'PT12S');

    <%_ } else if (fieldType === 'Boolean') { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).should('not.be.checked');
    cy.get(`[data-cy="<%= fieldName %>"]`).click().should('be.checked');
    <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent === 'text') { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('<%= fieldValue %>', { force: true }).invoke('val').should('match', new RegExp('<%= fieldValue %>'));

    <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType)) { _%>
    cy.setFieldImageAsBytesOfEntity('<%= fieldName %>', 'integration-test.png', 'image/png');

    <%_ } else if (fieldIsEnum) { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).select('<%= fieldValue %>');

    <%_ } else if (fieldType === 'UUID'){ _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('<%= fieldValue %>').invoke('val').should('match', new RegExp('<%= fieldValue %>'));

    <%_ } else if(['Integer', 'Long', 'Float', 'Double', 'BigDecimal', 'LocalDate', ].includes(fieldType)) { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('<%= fieldValue %>').should('have.value', '<%= fieldValue %>');

    <%_ } else { _%>
    cy.get(`[data-cy="<%= fieldName %>"]`).type('<%= fieldValue %>', { force: true }).invoke('val').should('match', new RegExp('<%= fieldValue %>'));

    <%_ } _%>
    <%_ }); _%>
    <%_ relationships.forEach((relationship) => {
      const relationshipType = relationship.relationshipType;
      const ownerSide = relationship.ownerSide;
      const relationshipName = relationship.relationshipName;
      const relationshipNameCapitalized = relationship.relationshipNameCapitalized;_%>
    <%_ if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true)) { _%>
    cy.setFieldSelectToLastOfEntity('<%= relationshipName %>');

    <%_ } else if ((relationshipType === 'many-to-many' && ownerSide === true)) { _%>
    cy.setFieldSelectToLastOfEntity('<%= relationshipName %>');

    <%_ } _%>
    <%_ }); _%>
    cy.get(entityCreateSaveButtonSelector).click({force: true});
    cy.scrollTo('top', {ensureScrollable: false});
    cy.get(entityCreateSaveButtonSelector).should('not.exist');
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequestAfterCreate');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequestAfterCreate');
    cy.get(entityTableSelector).should('have.lengthOf', startingEntitiesCount + 1);
    cy.visit('/');
  });
  <%= closeBlockComment %>

  <%= openBlockComment %>
  it('should delete last instance of <%= entityClass %>', () => {
    cy.server();
    cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequest');
    <%_ if (clientFramework === 'react') { _%>
    cy.route('GET', '/<%= baseApi + entityApiUrl %>/*').as('dialogDeleteRequest');
    <%_ } _%>
    cy.route('DELETE', '/<%= baseApi + entityApiUrl %>/*').as('deleteEntityRequest');
    cy.visit('/');
    cy.clickOnEntityMenuItem('<%= entityStateName %>');
    cy.wait('@entitiesRequest').its('responseBody').then(array => {
      startingEntitiesCount = array.length;
      if (startingEntitiesCount > 0) {
        cy.get(entityTableSelector).should('have.lengthOf', startingEntitiesCount);
        cy.get(entityDeleteButtonSelector).last().click({force: true});
        <%_ if (clientFramework === 'react') { _%>
        cy.wait('@dialogDeleteRequest');
        <%_ } _%>
        cy.getEntityDeleteDialogHeading('<%= entityInstance %>').should('exist');
        cy.get(entityConfirmDeleteButtonSelector).click({force: true});
        cy.wait('@deleteEntityRequest');
        cy.route('GET', '/<%= baseApi + entityApiUrl %>*').as('entitiesRequestAfterDelete');
        cy.visit('/');
        cy.clickOnEntityMenuItem('<%= entityStateName %>');
        cy.wait('@entitiesRequestAfterDelete');
        cy.get(entityTableSelector).should('have.lengthOf', startingEntitiesCount - 1);
      }
      cy.visit('/');
    });
  });
  <%= closeBlockComment %>
  <%_ } _%>
});
